/**
 * Created by Allan on 2017/09/20.
 */
import React, { Component } from "react";
import createG2 from "g2-react";
import "./index.less"

export default class MultiLineChart extends Component {
	constructor(props) {
		super(props);
		this.state = {
			width: document.body.clientWidth,
			height: 130 * 2,
			plotCfg: {
				margin: [50, 60, 60, 50]
			},
			xAxisFontSize: 28
		};
	}

	componentDidMount() {
		if (document.body.clientWidth > 750) {
			this.setState({
				xAxisFontSize: 50
			});
		}

		document.addEventListener("click", function (e) {
			if (e.target.tagName === "CANVAS") {
				return;
			} else {
				let nodes = document.querySelectorAll(".ac-tooltip");
				nodes.forEach((node) => {
					node.style.visibility = "hidden";
				})
			}

		})
	}

	componentWillUnmount() {
		document.removeEventListener("click");
	}

	render() {
		const Line = createG2(chart => {

			// 点击画布显示当前坐标信息
			chart.on('plotclick', function (ev) {
				var point = {
					x: ev.x,
					y: ev.y,
				};
				chart.showTooltip(point); // 接收的是画布坐标上的点
			});

			chart.axis("xAxisData", {
				title: null,
				line: {
					stroke: '#dcdcdc', // 设置线的颜色
				},
				// labels: {
				// 	offset: 30,
				// 	label: {
				// 		textAlign: 'center',
				// 		fill: "#A3A4A6", // 文本的颜色
				// 		fontSize: this.state.xAxisFontSize // 文本大小
				// 	},
				// },
				range: [0, 1],
				labels: {
					custom: true,
					renderer: function (value) {
						return '<div class="bottom-axis-text">' + value + '</div>';
					}
				}
			});

			chart.axis("yAxisData", {
				title: null,
				line: null,
				labels: null,
				grid: null,
				tickLine: null,
			});

			chart.tooltip(true, {
				custom: true, // 使用自定义的 tooltip
				offset: 100,
				crosshairs: true, // 是否显示 tooltip 辅助线复制代码
				title: null,
				padding: [5, 5, 5, 5],
			});
			chart.legend(false);

			//图表x轴从最左边开始显示
			chart.source(this.props.chartData, {
				xAxisData: {
					type: 'cat',
					range: [0, 1],
				}
			})

			var func = name => {
				if (name === '入职员工数') {
					return '#15BC83';
				} else {
					return '#FF943E';
				}
			}
			chart.line().position('xAxisData*yAxisData').color('name', func).shape('smooth').size(5);
			chart.point().position('xAxisData*yAxisData').color('name', func).size(10);
			chart.animate(false);
			chart.render();

		});

		return (
			<div id="multline-chart">
				<Line
					data={this.props.chartData ? this.props.chartData : []}
					width={this.state.width}
					height={this.state.height}
					plotCfg={this.state.plotCfg}
					forceFit={true}
				/>
			</div>
		);
	}
}
